package com.yycx.module.bus.provider.service.hy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.query.CriteriaDelete;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.*;
import com.yycx.module.bus.client.enums.HySaleTypeEnum;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.client.vo.OrderCustomReturn;
import com.yycx.module.bus.provider.handler.haiying.HyOrderUtils;
import com.yycx.module.bus.provider.handler.haiying.HyReturnOrderDetailsSplit;
import com.yycx.module.bus.provider.mapper.hy.BusHyorderReturnMapper;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.module.bus.provider.service.hy.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.yycx.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 回款明细接口实现类
 *
 * @author flyme
 * @date 2023-11-23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusHyorderReturnServiceImpl extends BaseServiceImpl<BusHyorderReturnMapper, BusHyorderReturn> implements BusHyorderReturnService {


    @Autowired
    private HyOrderDetailService orderDetailService;

    @Autowired
    private BusPaymentOrderService paymentOrderService;

    @Autowired
    private HyOrderService hyOrderService;

    @Autowired
    private HyOrderUtils hyOrderUtils;

    @Autowired
    @Lazy
    private BusBankStatementService bankStatementService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusHyorderReturn bhr, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusHyorderReturn> cq, BusHyorderReturn bhr, EntityMap requestMap) {
        return ResultBody.ok();
    }


    private List<BusHyorderReturn> getList(List<HyOrderDetail> orderDetailList) {
        List<BusHyorderReturn> list = new ArrayList<>();
        for (HyOrderDetail hyOrderDetail : orderDetailList) {
            BusHyorderReturn orderReturn = new BusHyorderReturn();
            BeanUtil.copyProperties(hyOrderDetail, orderReturn, CopyOptions.create().setIgnoreProperties("createTime"));
            orderReturn.setOrderDetailsReturnId(IdWorker.getId());
            orderReturn.setOverStandAmount(new BigDecimal("0"));
            list.add(orderReturn);
        }
        return list;
    }

    @Override
    public EntityMap totalReturnAmountInfo(String selectIds) {
        CriteriaQuery<BusHyorderReturn> cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select("count(DISTINCT customCode) customIdCount,sum(saleAmount) saleAmount,customCode,customId,saleManId,deptId");
        cq.in(true, "orderDetailsReturnId", selectIds.split(","));
        cq.isNull("returnId");
        return findOne(cq);
    }

    @Override
    public List<BusHyorderReturn> selectByIds(String[] selectIds) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.in(true, "orderDetailsReturnId", selectIds);
        cq.orderByAsc("saleAmount");
        return list(cq);
    }

    @Override
    public ResultBody addDiscountDetails(String orderDetailsReturnId, BigDecimal saleAmount) {
        BusHyorderReturn hyorderReturn = getById(orderDetailsReturnId);
        HyOrderDetail orderDetails = orderDetailService.getById(hyorderReturn.getOrderDetailsId());
        String orderId = orderDetails.getOrderId();
        HyOrder hyOrder = hyOrderService.getById(orderId);
        HyOrderDetail pzDetails = orderDetailService.addDiscountDetails(orderDetails, hyOrder, saleAmount);
        if (FlymeUtils.isNotEmpty(pzDetails)) {
            BusHyorderReturn insert = new BusHyorderReturn();
            BeanUtil.copyProperties(pzDetails, insert, CopyOptions.create().setIgnoreProperties("orderDetailsReturnId", "createTime").ignoreNullValue());
            insert.setOrderDetailsReturnId(IdWorker.getId());
            saveOrUpdate(insert);
            List<BusPaymentOrder> paymentOrder = paymentOrderService.selectByOrderId(orderId);
            if (FlymeUtils.isNotEmpty(paymentOrder)) {
                for (BusPaymentOrder busPaymentOrder : paymentOrder) {
                    BigDecimal amount = busPaymentOrder.getTakeAmount();
                    if (FlymeUtils.ge(amount, saleAmount)) {
                        BusPaymentOrder busPaymentOrder1 = new BusPaymentOrder();
                        BeanUtils.copyProperties(busPaymentOrder, busPaymentOrder1);
                        busPaymentOrder1.setUseAmount(saleAmount.multiply(new BigDecimal("-1")));
                        busPaymentOrder1.setPaymentOrderId(IdWorker.getId());
                        paymentOrderService.save(busPaymentOrder1);
                        break;
                    }
                }
            }
            return ResultBody.msg("票折成功");
        }
        ApiAssert.failure("票折失败");
        return ResultBody.failed("票折成功");
    }

    @Override
    public Boolean updateOverAmount(String orderDetailsReturnId,Integer settleOverDay ,BigDecimal settleOverPrice, BigDecimal overDateAmount) {
        CriteriaUpdate cu=new CriteriaUpdate();
        //cu.set("settleOverDay",settleOverDay);
        cu.set("settleOverPrice",settleOverDay);
        cu.set("overDateAmount",overDateAmount);
        cu.eq("orderDetailsReturnId",orderDetailsReturnId);
        return update(cu);
    }

    /**
     * 添加订单回显明细
     *
     * @param returnId
     * @return
     */
    @Override
    public List<EntityMap> selectByReturnId(Long returnId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select(BusHyorderReturn.class, "orderDetailsReturnId", "orderDetailsId", "drugNo", "drugsName", "drugLotNo", "drugsSpec", "salePrice", "saleAmount", "saleNum");
        cq.select(HyOrder.class, "orderNo", "outOrderNo", "sendDate");
        cq.eq(true, "returnId", returnId);
        cq.createJoin(HyOrder.class);
        cq.orderByAsc("ho.createTime");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody chaiFen(OrderCustomReturn bocr) {
        Long orderDetailsReturnId = bocr.getOrderDetailsId();
        BusHyorderReturn orderDetails = getById(orderDetailsReturnId);
        ApiAssert.isNotEmpty("orderDetails不能为空", orderDetails);
        chaiFenByParent(bocr, orderDetails);
        return ResultBody.ok();
    }

    /**
     * 拆分订单
     *
     * @param bocr
     * @param orderDetails
     */
    @Override
    public BusHyorderReturn chaiFenByParent(OrderCustomReturn bocr, BusHyorderReturn orderDetails) {
        ApiAssert.isNotEmpty("orderDetails不能为空", orderDetails);
        //销售数量
        BigDecimal totalSaleNum = orderDetails.getSaleNum();
        //销售金额
        BigDecimal totalSaleAmount = orderDetails.getSaleAmount();
        //销售单价
        BigDecimal salePrice = orderDetails.getSalePrice();
        //拆分数量
        BigDecimal chaiFenNum = FlymeUtils.getBigDecimal(bocr.getReturnNum(), "0");
        //拆分金额
        BigDecimal chaiFenAmount = FlymeUtils.getBigDecimal(bocr.getReturnAmount(), "0");
        //回款方式1按数量 2按金额
        Integer returnType = bocr.getReturnType();
        BigDecimal ratio = new BigDecimal("0");
        //按金额
        if (returnType.equals(2)) {
            //计算回款比例
            ratio = chaiFenAmount.divide(totalSaleAmount, 6, BigDecimal.ROUND_HALF_UP);
            //计算回款数量
            chaiFenNum = totalSaleNum.multiply(ratio).setScale(4, BigDecimal.ROUND_HALF_UP);
        } else {
            ratio = chaiFenNum.divide(totalSaleNum, 6, BigDecimal.ROUND_HALF_UP);
            chaiFenAmount = chaiFenNum.multiply(salePrice);
        }
        //拆出新明细
        BusHyorderReturn newOrderDetails = getOrderDetails(orderDetails, ratio, chaiFenNum, true);
        newOrderDetails.setSaleAmount(chaiFenAmount);
        newOrderDetails.setCreateTime(DateUtils.getNowDateTime());
        //保存新明细
        saveOrUpdate(newOrderDetails);
        //剩余数量
        BigDecimal surplusNum = totalSaleNum.subtract(chaiFenNum);
        BigDecimal surplusRadio = new BigDecimal("1").subtract(ratio);
        //修改当前明细
        BusHyorderReturn oldOrderDetails = getOrderDetails(orderDetails, surplusRadio, surplusNum, false);
        oldOrderDetails.setSaleAmount(totalSaleAmount.subtract(chaiFenAmount));
        //更新之前明细
        saveOrUpdate(oldOrderDetails);
        return newOrderDetails;
    }


    /**
     * 根据父明细拆出新明细
     *
     * @param orderDetails
     * @param ratio
     * @param saleNum
     * @param isNew
     * @return
     */
    private BusHyorderReturn getOrderDetails(BusHyorderReturn orderDetails, BigDecimal ratio, BigDecimal saleNum, Boolean isNew) {
        BusHyorderReturn hyorderReturn = new BusHyorderReturn();
        BeanUtil.copyProperties(orderDetails, hyorderReturn);
        if (isNew) {
            if (FlymeUtils.isNotEmpty(orderDetails.getParentId())) {
                hyorderReturn.setParentId(orderDetails.getParentId());
            } else {
                hyorderReturn.setParentId(orderDetails.getOrderDetailsReturnId().toString());
            }
            hyorderReturn.setOrderDetailsReturnId(IdWorker.getId());
        }
        computeAmount(hyorderReturn, ratio);
        return hyorderReturn;
    }

    public void computeAmount(BusHyorderReturn hyorderReturn, BigDecimal ratio) {

        //数量
        hyorderReturn.setSaleNum(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSaleNum()));

        //结算发货金额
        hyorderReturn.setSettleSendAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSettleSendAmount()));

        //部门结算金额
        hyorderReturn.setDeptSettleAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getDeptSettleAmount()));

        //票折金额
        hyorderReturn.setDiscountPrice(hyOrderUtils.computeAmount(ratio, hyorderReturn.getDiscountPrice()));
        //高开金额
        hyorderReturn.setCustomGapUpAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCustomGapUpAmount()));
        //资保金收款金额
        hyorderReturn.setCustomBondTakeAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCustomBondTakeAmount()));

        //渠道商结算金额
        hyorderReturn.setSettleAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSettleAmount()));
        //片区服务商结算金额
        hyorderReturn.setSettleAmountC(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSettleAmountC()));

        //商务经理结算金额
        hyorderReturn.setSettleAmountD(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSettleAmountD()));
        //商务总负责人结算金额
        hyorderReturn.setSettleAmountE(hyOrderUtils.computeAmount(ratio, hyorderReturn.getSettleAmountE()));
        //部门利润
        hyorderReturn.setDeptProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getDeptProfitAmount()));
        //部门超期金额
        hyorderReturn.setDeptSettleOverAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getDeptSettleOverAmount()));

        //底价
        hyorderReturn.setCustomFloorAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCustomFloorAmount()));
        //利润
        hyorderReturn.setProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getProfitAmount()));
        //税收利润
        hyorderReturn.setTaxProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getTaxProfitAmount()));
        //超期差额
        hyorderReturn.setOverDateAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getOverDateAmount()));

        //超标准差额
        hyorderReturn.setOverStandAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getOverStandAmount()));
        //产品利润
        hyorderReturn.setDrugProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getDrugProfitAmount()));

        //边际利润
        hyorderReturn.setBjProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getBjProfitAmount()));
        //管理利润
        hyorderReturn.setManageProfitAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getManageProfitAmount()));
        //预提税金
        hyorderReturn.setYtTaxAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getYtTaxAmount()));

        //校验金额
        hyorderReturn.setCheckAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCheckAmount()));
        //支付开票税金
        hyorderReturn.setPayInvoiceTaxAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getPayInvoiceTaxAmount()));
        //资保金
        hyorderReturn.setCustomBond(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCustomBond()));
        //成本金额
        hyorderReturn.setCostAmount(hyOrderUtils.computeAmount(ratio, hyorderReturn.getCostAmount()));
        //税率差额
        hyorderReturn.setTaxRateDiff(hyOrderUtils.computeAmount(ratio, hyorderReturn.getTaxRateDiff()));

        hyorderReturn.setRadio(ratio);
    }


    @Override
    public Boolean updateReturnId(BusPayment payment, String selectIds) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "returnId", payment.getPaymentId());
        cu.set(true, "customReturnState", CommonConstants.INT_0);
        cu.in(true, "orderDetailsReturnId", selectIds.split(","));
        return update(cu);
    }


    @Override
    public Boolean updateReturnInfo(BusPayment payment) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql("returnAmount=saleAmount");
        //更新订单回款状态为已认款
        cu.set(true, "customReturnState", CommonConstants.INT_1);
        cu.set(true, "returnBank", payment.getBankName());
        //认款月份
        cu.set(true, "renDate", DateUtil.now());
        cu.set(true, "returnDate", payment.getAmountDate());
        cu.eq(true, "returnId", payment.getPaymentId());
        return update(cu);
    }

    /**
     * 清空回款信息
     */
    @Override
    public Boolean clearHuiKuanInfo(Serializable returnId) {
        if (FlymeUtils.allNotNull(returnId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "returnId", null);
            cu.set(true, "returnAmount", new BigDecimal("0"));
            cu.set(true, "returnDate", null);
            cu.set(true, "renDate", null);
            cu.set(true, "returnBank", null);
            cu.set(true, "customReturnState", CommonConstants.INT_0);
            cu.eq(true, "returnId", returnId.toString());
            update(cu);
        }
        return true;
    }

    @Override
    public ResultBody cancelChaiFen(String orderDetailsReturnId) {
        BusHyorderReturn orderDetails = getById(orderDetailsReturnId);
        if (FlymeUtils.isNotEmpty(orderDetails)) {
            String parentId = orderDetails.getParentId();
            if (FlymeUtils.isNotEmpty(parentId)) {
                BusHyorderReturn parentOrderDetails = getById(parentId);
                computeAmount(parentOrderDetails, orderDetails);
                saveOrUpdate(parentOrderDetails);
                removeById(orderDetailsReturnId);
            }
        }
        return ResultBody.ok();
    }

    private void computeAmount(BusHyorderReturn parent, BusHyorderReturn hyorderReturn) {
        //数量
        parent.setSaleNum(sumAmount(parent.getSaleNum(), hyorderReturn.getSaleNum()));
        //销售金额
        parent.setSaleAmount(sumAmount(parent.getSaleAmount(), hyorderReturn.getSaleAmount()));

        //结算发货金额
        parent.setSettleSendAmount(sumAmount(parent.getSettleSendAmount(), hyorderReturn.getSettleSendAmount()));


        //底价
        parent.setCustomFloorAmount(sumAmount(parent.getCustomFloorAmount(), hyorderReturn.getCustomFloorAmount()));

        //票折金额
        parent.setDiscountPrice(sumAmount(parent.getDiscountPrice(), hyorderReturn.getDiscountPrice()));
        //高开金额
        parent.setCustomGapUpAmount(sumAmount(parent.getCustomGapUpAmount(), hyorderReturn.getCustomGapUpAmount()));
        //资保金收款金额
        parent.setCustomBondTakeAmount(sumAmount(parent.getCustomBondTakeAmount(), hyorderReturn.getCustomBondTakeAmount()));

        //渠道商结算金额
        parent.setSettleAmount(sumAmount(parent.getSettleAmount(), hyorderReturn.getSettleAmount()));
        //片区服务商结算金额
        parent.setSettleAmountC(sumAmount(parent.getSettleAmountC(), hyorderReturn.getSettleAmountC()));

        //商务经理结算金额
        parent.setSettleAmountD(sumAmount(parent.getSettleAmountD(), hyorderReturn.getSettleAmountD()));
        //商务总负责人结算金额
        parent.setSettleAmountE(sumAmount(parent.getSettleAmountE(), hyorderReturn.getSettleAmountE()));
        //部门利润金额
        parent.setDeptProfitAmount(sumAmount(parent.getDeptProfitAmount(), hyorderReturn.getDeptProfitAmount()));
        //部门结算金额
        parent.setDeptSettleAmount(sumAmount(parent.getDeptSettleAmount(), hyorderReturn.getDeptSettleAmount()));
        //利润
        parent.setProfitAmount(sumAmount(parent.getProfitAmount(), hyorderReturn.getProfitAmount()));
        //税收利润
        parent.setTaxProfitAmount(sumAmount(parent.getTaxProfitAmount(), hyorderReturn.getTaxProfitAmount()));
        //超期差额
        parent.setOverDateAmount(sumAmount(parent.getOverDateAmount(), hyorderReturn.getOverDateAmount()));

        //超标准差额
        parent.setOverStandAmount(sumAmount(parent.getOverStandAmount(), hyorderReturn.getOverStandAmount()));
        //产品利润
        parent.setDrugProfitAmount(sumAmount(parent.getDrugProfitAmount(), hyorderReturn.getDrugProfitAmount()));

        //边际利润
        parent.setBjProfitAmount(sumAmount(parent.getBjProfitAmount(), hyorderReturn.getBjProfitAmount()));
        //管理利润
        parent.setManageProfitAmount(sumAmount(parent.getManageProfitAmount(), hyorderReturn.getManageProfitAmount()));
        //预提税金
        parent.setYtTaxAmount(sumAmount(parent.getYtTaxAmount(), hyorderReturn.getYtTaxAmount()));

        //校验金额
        parent.setCheckAmount(sumAmount(parent.getCheckAmount(), hyorderReturn.getCheckAmount()));
        //支付开票税金
        parent.setPayInvoiceTaxAmount(sumAmount(parent.getPayInvoiceTaxAmount(), hyorderReturn.getPayInvoiceTaxAmount()));
        //资保金
        parent.setCustomBond(sumAmount(parent.getCustomBond(), hyorderReturn.getCustomBond()));
        //成本金额
        parent.setCostAmount(sumAmount(parent.getCostAmount(), hyorderReturn.getCostAmount()));
        parent.setRadio(sumAmount(parent.getRadio(), hyorderReturn.getRadio()));
    }

    /**
     * 按比例计算金额
     *
     * @param parentAmount  父对象
     * @param computeAmount 当前需要计算的字段金额
     * @return
     */
    private static BigDecimal sumAmount(BigDecimal parentAmount, BigDecimal computeAmount) {
        if (FlymeUtils.isNotEmpty(computeAmount) && FlymeUtils.gtzero(computeAmount)) {
            return parentAmount.add(computeAmount);
        }
        return new BigDecimal("0");
    }

    @Override
    public EntityMap totalDeptSettleApplyAmount(String settleIds) {
        CriteriaQuery<BusHyorderReturn> cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select("sum(deptSettleAmount) deptSettleAmount", "deptId", "saleManId", "drugType");
        cq.isNull("deptSettleApplyId");
        cq.in(true, "orderDetailsReturnId", settleIds.split(","));
        return findOne(cq);
    }


    @Override
    public BigDecimal totalSettleApplyAmount(String settleIds, Integer settleType) {
        CriteriaQuery<BusHyorderReturn> cq = new CriteriaQuery(BusHyorderReturn.class);
        if (settleType.equals(1)) {
            //加提成金额+超期差额
            cq.select("sum(settleAmount+settleRebateAmount+overDateAmount)");
            cq.isNull("settleApplyId");
        }
        if (settleType.equals(2)) {
            cq.select("sum(settleAmountD)");
            cq.isNull("settleApplyIdD");
        }
        if (settleType.equals(3)) {
            cq.select("sum(settleAmountC)");
            cq.isNull("settleApplyIdC");
        }
        if (settleType.equals(4)) {
            cq.select("sum(settleAmountE)");
            cq.isNull("settleApplyIdE");
        }
        cq.in(true, "orderDetailsReturnId", settleIds.split(","));
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        return FlymeUtils.getBigDecimal(amount, new BigDecimal("0"));
    }

    @Override
    public EntityMap countSettleManId(String settleIds, Integer settleType) {
        CriteriaQuery<BusHyorderReturn> cq = new CriteriaQuery(BusHyorderReturn.class);
        if (settleType.equals(1)) {
            cq.select("count(DISTINCT saleManId) count,count(DISTINCT drugType) drugTypeCount,drugType,saleManId manId,deptId");
            cq.isNotNull("saleManId");
        }
        if (settleType.equals(2)) {
            cq.select("count(DISTINCT saleManIdD) count,count(DISTINCT drugType) drugTypeCount,drugType,saleManIdD manId,deptId");
            cq.isNotNull("saleManIdD");
        }
        if (settleType.equals(3)) {
            cq.select("count(DISTINCT saleManIdC) count,count(DISTINCT drugType) drugTypeCount,drugType,saleManIdC manId,deptId");
            cq.isNotNull("saleManIdC");
        }
        if (settleType.equals(4)) {
            cq.select("count(DISTINCT saleManIdE) count,count(DISTINCT drugType) drugTypeCount,drugType,saleManIdE manId,deptId");
            cq.isNotNull("saleManIdE");
        }
        cq.in(true, "orderDetailsReturnId", settleIds.split(","));
        return findOne(cq);
    }

    @Override
    public Boolean updateDeptSettleApplyId(Long paymentId, String selectIds) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "deptSettleApplyId", paymentId);
        cu.in(true, "orderDetailsReturnId", selectIds.split(","));
        return update(cu);
    }

    @Override
    public Boolean updateSettleApplyId(Long paymentId, List<Long> selectIds, Integer settleType) {
        CriteriaUpdate cu = new CriteriaUpdate();
        if (settleType.equals(1)) {
            cu.set(true, "settleApplyId", paymentId);
        }
        if (settleType.equals(2)) {
            cu.set(true, "settleApplyIdD", paymentId);
        }
        if (settleType.equals(3)) {
            cu.set(true, "settleApplyIdC", paymentId);
        }
        if (settleType.equals(4)) {
            cu.set(true, "settleApplyIdE", paymentId);
        }
        cu.in(true, "orderDetailsReturnId", selectIds);
        return update(cu);
    }

    @Override
    public Boolean clearSettleApplyId(Serializable paymentId, Integer settleType) {
        if (FlymeUtils.allNotNull(paymentId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            if (settleType.equals(1)) {
                cu.set(true, "settleApplyId", null);
                cu.eq(true, "settleApplyId", paymentId);
            }
            if (settleType.equals(2)) {
                cu.set(true, "settleApplyIdD", null);
                cu.eq(true, "settleApplyIdD", paymentId);
            }
            if (settleType.equals(3)) {
                cu.set(true, "settleApplyIdC", null);
                cu.eq(true, "settleApplyIdC", paymentId);
            }
            if (settleType.equals(4)) {
                cu.set(true, "settleApplyIdE", null);
                cu.eq(true, "settleApplyIdE", paymentId);
            }
            update(cu);
        }
        return true;
    }

    @Override
    public Boolean clearDeptSettleApplyId(Serializable paymentId) {
        if (FlymeUtils.allNotNull(paymentId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "deptSettleApplyId", null);
            cu.eq(true, "deptSettleApplyId", paymentId);
            update(cu);
        }
        return true;
    }


    @Override
    public Boolean clearSettleApplyId(Long orderDetailsReturnId, Integer settleType) {
        if (FlymeUtils.allNotNull(orderDetailsReturnId)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            if (settleType.equals(1)) {
                cu.set(true, "settleApplyId", null);
                cu.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
            }
            if (settleType.equals(2)) {
                cu.set(true, "settleApplyIdD", null);
                cu.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
            }
            if (settleType.equals(3)) {
                cu.set(true, "settleApplyIdC", null);
                cu.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
            }
            if (settleType.equals(4)) {
                cu.set(true, "settleApplyIdE", null);
                cu.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
            }
            update(cu);
        }
        return true;
    }


    @Override
    public List<BusHyorderReturn> getByOrderDetailsId(String orderDetailsId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.eq(true, "orderDetailsId", orderDetailsId);
        return list(cq);
    }

    @Override
    public List<BusHyorderReturn> selectByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.eq(true, "orderId", orderId);
        return list(cq);
    }


    @Override
    public Boolean updateReturnState(Long orderDetailsReturnId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "customReturnState", CommonConstants.INT_1);
        cu.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
        return update(cu);
    }


    @Override
    public Boolean updateInvoice(BusPayment payment) {
        //开票订单明细中间表(bus_hyorder_inovice_details)ID
        String selectIds = payment.getSelectIds();
        //结算对象
        Integer settleType = payment.getSettleType();
        //发票金额
        BigDecimal amount = payment.getInvoiceAmount();
        /*if (FlymeUtils.isNotEmpty(selectIds)) {
            List<BusHyorderInoviceDetails> list = hyorderInoviceDetailsService.selectByIds(selectIds);
            int i = 0;
            for (BusHyorderInoviceDetails inoviceDetails : list) {
                String orderDetailsId = inoviceDetails.getOrderDetailsId();
                //查询订单明细
                BusHyorderReturn orderDetail = getById(orderDetailsId);
                //渠道商
                if (settleType.equals(1)) {
                    String settleInvoiceNo = orderDetail.getSettleInvoiceNo();
                    String settleInvoiceDate = orderDetail.getSettleInvoiceDate();
                    if (FlymeUtils.isNotEmpty(settleInvoiceNo)) {
                        invoiceNo = settleInvoiceNo + "," + invoiceNo;
                    }
                    if (FlymeUtils.isNotEmpty(settleInvoiceDate)) {
                        invoiceDate = settleInvoiceDate + "," + invoiceDate;
                    }
                    if (i == 0) {
                        //第一条记录填写发票金额
                        orderDetail.setSettleInvoiceAmount(amount.toString());
                    }
                    orderDetail.setSettleInvoiceDate(invoiceDate);
                    orderDetail.setSettleInvoiceNo(invoiceNo);
                }
                //商务经理
                if (settleType.equals(2)) {
                    String no = orderDetail.getSettleInvoiceNoD();
                    String date = orderDetail.getSettleInvoiceDateD();
                    if (FlymeUtils.isNotEmpty(no)) {
                        invoiceNo = no + "," + invoiceNo;
                    }
                    if (FlymeUtils.isNotEmpty(date)) {
                        invoiceDate = date + "," + invoiceDate;
                    }
                    if (i == 0) {
                        orderDetail.setSettleInvoiceAmountD(amount.toString());
                    }
                    orderDetail.setSettleInvoiceDateD(invoiceDate);
                    orderDetail.setSettleInvoiceNoD(invoiceNo);
                }
                //片区服务商
                if (settleType.equals(3)) {
                    String no = orderDetail.getSettleInvoiceNoC();
                    String date = orderDetail.getSettleInvoiceDateC();
                    if (FlymeUtils.isNotEmpty(no)) {
                        invoiceNo = no + "," + invoiceNo;
                    }
                    if (FlymeUtils.isNotEmpty(date)) {
                        invoiceDate = date + "," + invoiceDate;
                    }
                    if (i == 0) {
                        orderDetail.setSettleInvoiceAmountC(amount.toString());
                    }
                    orderDetail.setSettleInvoiceDateC(invoiceDate);
                    orderDetail.setSettleInvoiceNoC(invoiceNo);
                }
                //商务总负责人
                if (settleType.equals(4)) {
                    String no = orderDetail.getSettleInvoiceNoE();
                    String date = orderDetail.getSettleInvoiceDateE();
                    if (FlymeUtils.isNotEmpty(no)) {
                        invoiceNo = no + "," + invoiceNo;
                    }
                    if (FlymeUtils.isNotEmpty(date)) {
                        invoiceDate = date + "," + invoiceDate;
                    }
                    if (i == 0) {
                        orderDetail.setSettleInvoiceAmountE(amount.toString());
                    }
                    orderDetail.setSettleInvoiceDateE(invoiceDate);
                    orderDetail.setSettleInvoiceNoE(invoiceNo);
                }
                updateById(orderDetail);
                i++;
            }
        }*/
        return true;
    }

    @Override
    public void insertToPaymentOrderList(BusPayment payment) {
        String bankStatementId = payment.getBankStatementId();
        BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select(BusHyorderReturn.class, "orderId", "sum(saleAmount) saleAmount", "returnId", "sendType", "customId");
        cq.eq(true, "returnId", payment.getPaymentId());
        cq.groupBy("orderId");
        List<BusHyorderReturn> list = list(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            List<BusPaymentOrder> paymentOrderList = new ArrayList<>();
            for (BusHyorderReturn busHyorderReturn : list) {
                BusPaymentOrder paymentOrder = getPaymentOrder(busHyorderReturn, payment, bankStatement);
                paymentOrderList.add(paymentOrder);
            }
            paymentOrderService.saveBatch(paymentOrderList);
        }

    }

    public BusPaymentOrder getPaymentOrder(BusHyorderReturn busHyorderReturn, BusPayment payment, BusBankStatement bankStatement) {
        BusPaymentOrder paymentOrder = new BusPaymentOrder();
        paymentOrder.setOrderId(busHyorderReturn.getOrderId());
        paymentOrder.setPaymentId(busHyorderReturn.getReturnId());
        paymentOrder.setBankStatementId(payment.getBankStatementId());
        paymentOrder.setBankId(payment.getBankId());
        paymentOrder.setBankName(payment.getBankName());
        paymentOrder.setRenDate(payment.getAmountDate());
        paymentOrder.setPaymentNo(payment.getPaymentNo());
        paymentOrder.setTakeDate(payment.getAmountDate());
        paymentOrder.setCompanyId(payment.getCompanyId());
        paymentOrder.setTakeAmount(bankStatement.getAmount());
        paymentOrder.setAmountType(1);
        paymentOrder.setSendType(busHyorderReturn.getSendType());
        paymentOrder.setCustomId(String.valueOf(busHyorderReturn.getCustomId()));
        paymentOrder.setTakeAmount(payment.getAmount());
        paymentOrder.setUseAmount(busHyorderReturn.getSaleAmount());
        return paymentOrder;
    }


    @Override
    public Boolean syncOrderReturn(String orderId) {
        HyOrder order = hyOrderService.getById(orderId);
        String orderType = order.getOrderType();
        List<HyOrderDetail> orderDetailList = orderDetailService.selectInsertToReturnList(orderId);
        syncToReturn(orderDetailList);
        return true;
    }

    @Override
    public Boolean syncBackOrderReturn(String orderId) {
        HyOrder order = hyOrderService.getById(orderId);
        String parentId = order.getParentId();
        return true;
    }

    @Override
    public Boolean deleteByOrderId(String orderId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq("orderId", orderId);
        return remove(cd);
    }

    /**
     * 如果回款明细已经拆分则按拆分比例进行更新
     *
     * @param returnList
     * @param hyorderReturn
     */
    public void updateBusHyorderReturn(List<BusHyorderReturn> returnList, BusHyorderReturn hyorderReturn) {
        for (BusHyorderReturn busHyorderReturn : returnList) {
            BeanUtil.copyProperties(hyorderReturn, busHyorderReturn, CopyOptions.create().setIgnoreProperties("saleAmount", "orderDetailsReturnId", "radio").ignoreNullValue());
            computeAmount(busHyorderReturn, FlymeUtils.getBigDecimal(busHyorderReturn.getRadio(),"1"));
            saveOrUpdate(busHyorderReturn);
        }
    }

    @Override
    public EntityMap selectOrderDetailsInfo(Long orderDetailsReturnId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select(BusHyorderReturn.class, "orderDetailsId", "orderId", "parentId", "drugLotNo", "drugNo", "drugsName", "drugsSpec", "saleNum", "salePrice", "saleAmount", "costPrice", "costAmount");
        cq.eq(true, "orderDetailsReturnId", orderDetailsReturnId);
        return findOne(cq);
    }

    @Override
    public List<BusHyorderReturn> getByOrderDetailsId(Long settleApplyId, Integer settleType) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        if (settleType.equals(1)) {
            cq.eq(true, "settleApplyId", settleApplyId);
        }
        if (settleType.equals(2)) {
            cq.eq(true, "settleApplyIdD", settleApplyId);
        }
        if (settleType.equals(3)) {
            cq.eq(true, "settleApplyIdC", settleApplyId);
        }
        if (settleType.equals(4)) {
            cq.eq(true, "settleApplyIdE", settleApplyId);
        }
        return list(cq);
    }


    @Override
    public ResultBody syncToReturn(String orderDetailsId) {
        HyOrderDetail hyOrderDetail = orderDetailService.getById(orderDetailsId);
        List<HyOrderDetail> list = new ArrayList<>();
        list.add(hyOrderDetail);
        syncToReturn(list);
        return ResultBody.msg("同步成功");
    }

    @Override
    public EntityMap countBackNum(String orderDetailsId, Long orderDetailsReturnId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select(BusHyorderReturn.class, "sum(saleNum) saleNum");
        cq.eq("bhr.saleType", HySaleTypeEnum.CHC.getCode());
        cq.eq(FlymeUtils.isEmpty(orderDetailsReturnId), "bhr.orderDetailsId", orderDetailsId);
        cq.eq(FlymeUtils.isNotEmpty(orderDetailsReturnId), "bhr.parentId", orderDetailsReturnId);
        return findOne(cq);
    }


    private void syncToReturn(List<HyOrderDetail> orderDetailList) {
        List<BusHyorderReturn> list = getList(orderDetailList);
        if (FlymeUtils.isNotEmpty(list)) {
            for (BusHyorderReturn hyorderReturn : list) {
                String orderDetailsId = hyorderReturn.getOrderDetailsId();
                //回款记录大于1代表已经拆分
                List<BusHyorderReturn> busHyorderReturns = getByOrderDetailsId(orderDetailsId);
                if (FlymeUtils.isNotEmpty(busHyorderReturns)) {
                    if (busHyorderReturns.size() == 1) {
                        BusHyorderReturn old = busHyorderReturns.get(0);
                        BeanUtil.copyProperties(hyorderReturn, old, CopyOptions.create().setIgnoreProperties("orderDetailsReturnId", "createTime").ignoreNullValue());
                        saveOrUpdate(old);
                    } else {
                        updateBusHyorderReturn(busHyorderReturns, hyorderReturn);
                    }
                } else {
                    save(hyorderReturn);
                }
            }
        }
    }

    /**
     * 添加订单回显明细
     *
     * @param orderId
     * @return
     */
    @Override
    public List<EntityMap> selectMapByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select(BusHyorderReturn.class, "orderDetailsReturnId", "orderDetailsId", "drugNo", "drugsName", "drugLotNo", "drugsSpec", "drugJr", "producersName", "salePrice", "saleAmount", "saleNum");
        cq.select(HyOrder.class, "orderNo", "outOrderNo", "sendDate");
        cq.eq(true, "ho.orderId", orderId);
        cq.createJoin(HyOrder.class);
        return selectEntityMap(cq);
    }

    /**
     * 统计回款金额
     *
     * @param returnId
     * @return
     */
    @Override
    public BigDecimal totalReturnAmount(List<Long> returnId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select("sum(saleAmount) returnAmount");
        cq.in(true, "bhr.returnId", returnId);
        EntityMap map = findOne(cq);
        if (FlymeUtils.isNotEmpty(map)) {
            return map.getBigDecimal("returnAmount");
        } else {
            return new BigDecimal("0");
        }
    }

    /**
     * 统计回款金额
     *
     * @param returnId
     * @return
     */
    @Override
    public BigDecimal totalSaleAmount(Long returnId) {
        CriteriaQuery<HyOrderDetail> cq = new CriteriaQuery(BusHyorderReturn.class);
        cq.select("sum(saleAmount) saleAmount");
        cq.eq(true, "bhr.returnId", returnId);
        EntityMap map = findOne(cq);
        if (FlymeUtils.isNotEmpty(map)) {
            return map.getBigDecimal("saleAmount");
        } else {
            return new BigDecimal("0");
        }
    }

}
